<?php

namespace support\command;

use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class StorageCommand extends SymfonyCommand
{
    protected function configure()
    {
        $this
            ->setName('storage:link')
            ->addArgument('user', InputArgument::OPTIONAL, 'user name', 'www');
    }

    /**
     * @return int 0 if everything went fine, or an exit code
     * @throws LogicException When this abstract method is not implemented
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $user = $input->getArgument('user');

        $publicDir = root_path() . '/public';
        $targetDir = runtime_path() . '/storage/upload'; // 实际存储目录
        $linkPath  = $publicDir . '/storage';              // public 下的链接名
        // 确保目标目录存在
        $oldUmask = umask(0);
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0755, true);
            @chown($targetDir, $user);
        }

        // 如果链接已存在，先删除
        if (file_exists($linkPath) || is_link($linkPath)) {
            unlink($linkPath);
        }
        // 创建符号链接
        $isSuccess = symlink($targetDir, $linkPath);
        umask($oldUmask);

        if ($isSuccess) {
            $output->writeln('storage link is created successfully');
            return self::SUCCESS;
        } else {
            $output->writeln('storage link is created fail, check permmisson or do it yourself');
            return self::FAILURE;
        }
    }
}
